package com.cskaoyan.javase.thread._4synchronized._3dielocK.slove2;

/**
 * 解决线程死锁
 * @since 17:32
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    public static void main(String[] args) {
        new Thread(new DieLockTask(true), "好人").start();
        new Thread(new DieLockTask(false), "坏蛋").start();
    }
}

class DieLockTask implements Runnable {
    private static final Object LOCKA = new Object();
    private static final Object LOCKB = new Object();
    private static final Object LOCKC = new Object();

    private boolean flag;

    public DieLockTask(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (LOCKC) {
                synchronized (LOCKA) {
                    System.out.println("我是" + Thread.currentThread().getName() + "，我获取了A锁!接下来请给我B锁!");
                    synchronized (LOCKB) {
                        System.out.println("我是" + Thread.currentThread().getName() + "6666666666!");
                    }
                }
            }

        } else {
            synchronized (LOCKC) {
                synchronized (LOCKB) {
                    System.out.println("我是" + Thread.currentThread().getName() + "，我获取了B锁!接下来请给我A锁!");
                    synchronized (LOCKA) {
                        System.out.println("我是" + Thread.currentThread().getName() + "777777777!");
                    }
                }
            }
        }
    }
}